/**
 * 
 */
package com.thon.dao.project.impl;


import java.util.Date;

import org.springframework.stereotype.Repository;

import com.thon.dao.project.ProjectCommentDao;
import com.thon.dao.util.AbstractDao;
import com.thon.dao.util.Page;
import com.thon.entity.project.ProjectComment;

/**
 * @file ProjectCommentDaoImpl.java
 * @author Zemo
 * @mail zemochen@gmail.com
 * @data 2013年10月11日 上午11:32:53
 * @description: TODO
 */
@Repository
public class ProjectCommentDaoImpl extends AbstractDao<ProjectComment> implements ProjectCommentDao{
	
	public ProjectCommentDaoImpl(){
		super(ProjectComment.class);
	}

	@Override
	public Page<ProjectComment> findProjectCommentByProject(Page<ProjectComment> page ,String by,int id) {
		
		if(by.equals("comment_to")){
			String queryString = "SELECT * FROM ym_project_comments WHERE ("+by+"=?  OR ("+by+" IS NULL AND project_id IN (SELECT id FROM ym_projects WHERE institute_id in (SELECT id from ym_institutions WHERE user_id = ?)))) AND is_delete = 0 ORDER BY created_date DESC ";
			return findPageBySql(page, queryString, null, id,id);
		}else if(by.equals("super_id")){
			String queryString = "SELECT * FROM ym_project_comments WHERE ("+by+"=? OR id = ?)AND is_delete=0  ORDER BY created_date DESC ";
			return findPageBySql(page, queryString, null, id,id);
		}
		else {
			String queryString = "SELECT * FROM ym_project_comments WHERE "+by+"=? AND is_delete=0  ORDER BY created_date DESC ";
			return findPageBySql(page, queryString, null, id);
		}
	}

	@Override
	public Long countUnreadProjectComment(Integer isRead,Integer projectId,Integer userId) {
		
		String queryString = "SELECT COUNT(id) FROM ym_project_comments WHERE is_read = ? AND is_delete=0 AND((project_id = ? AND super_id IS NULL) OR comment_to = ?)";
		return countBySql(queryString, isRead,projectId,userId);
	}
	
	
	@Override
	public Long countUnreadPreferentionComment(Integer isRead,Integer preferentionId,Integer userId) {
		
		String queryString = "SELECT COUNT(id) FROM ym_project_comments WHERE is_read = ? AND is_delete=0 AND preferential_id = ? AND comment_to = ?";
		return countBySql(queryString, isRead,preferentionId,userId);
	}
	
	@Override
	public Page<ProjectComment> findCommentByUser(
			Page<ProjectComment> comments, Integer userId) {
		comments.desc("comments.created_date");
		String sqlString="SELECT comments.* "
				+ "FROM ym_project_comments comments "
				//+ "RIGHT OUTER JOIN ym_projects projects "
				//+ "ON comments.project_id=projects.id "
				+ "WHERE  comments.user_id =? AND comments.is_delete = 0";
		return findPageBySql(comments, sqlString, null,userId);
	}

}
